package cn.fl.risk.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.IPriorityApiService;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.dto.SysOrgDTO;
import cmm.user.facade.system.dto.SysUsrDatAuthRDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapClaimInfoQC;
import cn.fl.capital.condition.CapRemindDataInfoQueryCondition;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.risk.condition.RskCommRecQueryCondition;
import cn.fl.risk.constant.RiskConstant;
import cn.fl.risk.dto.RskCommRecDTO;
import cn.fl.risk.service.IRskCommRecApiService;
import cn.fl.risk.service.IRskCommRecService;
import cn.fl.risk.transform.RskCommRecVOTransform;
import cn.fl.risk.vo.RskCommRecVO;
import com.alibaba.fastjson.JSON;
import fl.customer.facade.customer.api.ICustomerQueryApiService;
import fl.customer.facade.customer.dto.CstContactInfoDTO;
import fl.spl.facade.framework.constant.SplSystemConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Description: 沟通记录表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class RskCommRecServiceImpl implements IRskCommRecService {

    /**
     * 日志
     */
    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(RskCommRecServiceImpl.class);

    /**
     * API 暴露服务
     */
    @Autowired
    private IRskCommRecApiService rskCommRecApiService;

    /**
     * 数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    @Autowired
    private ISysUsrApiService sysUsrApiService;
    @Autowired
    private ICustomerQueryApiService customerQueryApiService;
    @Autowired
    private ISysOrgApiService sysOrgApiService;

    /**
     * 系统数据权限关系服务
     */
    @Autowired
    private IPriorityApiService priorityApiService;

    @Override
    public RskCommRecVO selectById(Long id) throws BaseException {
        if (StringUtils.isEmpty(id)) return null;
        RskCommRecDTO dto = this.rskCommRecApiService.selectRskCommRecById(id);
        return RskCommRecVOTransform.toVO(dto);
    }

    @Override
    public Long add(RskCommRecVO entity) throws BaseException {
        if (null == entity) return null;
        return this.rskCommRecApiService.addRskCommRec(RskCommRecVOTransform.toDTO(entity));
    }

    @Override
    public boolean removeByIds(List<Long> ids) throws BaseException {
        if (CollectionUtils.isEmpty(ids)) return false;
        return this.rskCommRecApiService.removeRskCommRecByIds(ids, CurrentThreadContext.getCurrentUserId());
    }

    @Override
    public boolean modify(RskCommRecVO entity) throws BaseException {
        if (null == entity) return false;
        return this.rskCommRecApiService.modifyRskCommRec(RskCommRecVOTransform.toDTO(entity));
    }

    @Override
    public Pager searchListPage(Pager page) throws BaseException {
        RskCommRecQueryCondition condition = null;
        if (null == page) {
            page = new Pager();
            page.setCondition(new RskCommRecQueryCondition());
        }
        condition = (RskCommRecQueryCondition) page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
        //添加数据权限
        //this.setDataAuth(condition);
        page = this.rskCommRecApiService.searchRskCommRecListPage(page);
        if (CollectionUtils.isNotEmpty(page.getResultList())) {
            BaseLogUtils.newLogger(String.format("催收记录查询结果：%s", JSON.toJSONString(page.getResultList()))).info();

            List<RskCommRecVO> voList = RskCommRecVOTransform.toVOList((List<RskCommRecDTO>) page.getResultList());
            this.setDictData(voList);
            page.setResultList(voList);
        }
        return page;
    }

    @Override
    public List<RskCommRecVO> searchList(RskCommRecQueryCondition condition) throws BaseException {
        if (null == condition) condition = new RskCommRecQueryCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
        List<RskCommRecVO> voList = RskCommRecVOTransform.toVOList(this.rskCommRecApiService.searchRskCommRecList(condition));
        this.setDictData(voList);
        return voList;
    }

    /**
     * 获取催收方式
     *
     * @return
     * @throws BaseException
     */
    @Override
    public List<KeyValueVO> getCollectWayCdList() throws BaseException {
        return this.sysDictionaryApiService.getKvList("RSK0009", CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
    }
    
    /**
     * 获取外呼结果
     *
     * @return
     * @throws BaseException
     */
    @Override
    public List<KeyValueVO> getCommStsCdList() throws BaseException {
        return this.sysDictionaryApiService.getKvList(RiskConstant.CODE_COMM_STS_CD, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
    }

    /**
     * 获取催收结果
     *
     * @return
     * @throws BaseException
     */
    @Override
    public List<KeyValueVO> getCollectRstCdList() throws BaseException {
        return this.sysDictionaryApiService.getKvList(RiskConstant.CODE_COLLECT_RST_CD, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
    }

    /**
     * 获取欠款原因
     *
     * @return
     * @throws BaseException
     */
    @Override
    public List<KeyValueVO> getOvdReasonCdList() throws BaseException {
        return this.sysDictionaryApiService.getKvList(RiskConstant.CODE_OVD_REASON_CD, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
    }

    /**
     * 获取客户还款方式
     *
     * @return
     * @throws BaseException
     */
    @Override
    public List<KeyValueVO> getPayTypCdList() throws BaseException {
        return this.sysDictionaryApiService.getKvList(RiskConstant.CODE_PAY_TYP_CD, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
    }

    /**
     * 添加数据字典名称
     *
     * @param voList
     */
    public void setDictData(List<RskCommRecVO> voList) {
        if (CollectionUtils.isEmpty(voList)) return;
        Map<String, String> collectWayCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), "RSK0009");
        Map<String, String> collectRstCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), "RSK0012");
        Map<String, String> reasonCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), "RSK0011");
        //Map<String, String> payTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), RiskConstant.CODE_PAY_TYP_CD);
        Map<String, String> commStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), RiskConstant.CODE_COMM_STS_CD);

        List<SysOrgDTO> orgList = this.sysOrgApiService.searchListByOrgTypCd(CurrentThreadContext.getCurrentSysCd());
        Map<String, String> orgMap = null;
        if (CollectionUtils.isNotEmpty(orgList)) {
            orgMap = new HashMap<>(orgList.size());
            for (SysOrgDTO orgDTO : orgList) {
                orgMap.put(orgDTO.getOrgCd(), orgDTO.getOrgNm());
            }
        }

        for (RskCommRecVO vo : voList) {
            if (collectWayCdMap != null && collectWayCdMap.containsKey(vo.getCollectWayCd())) {
                vo.setCollectWayCdNm(collectWayCdMap.get(vo.getCollectWayCd()));
            }
            if (collectRstCdMap != null && collectRstCdMap.containsKey(vo.getCollectRstCd())) {
                vo.setCollectRstCdNm(collectRstCdMap.get(vo.getCollectRstCd()));
            }
            String ovdReasonCd = vo.getOvdReasonCd();
            if(StringUtils.isNotEmpty(ovdReasonCd)){
                Iterator<String> iterator = Arrays.asList(ovdReasonCd.split(";")).iterator();
                String ovdReasonCdNm = "";
                while(iterator.hasNext()){
                    String next = iterator.next();
                    ovdReasonCdNm += reasonCdMap.get(next);
                    if(iterator.hasNext()){
                        ovdReasonCdNm +=";";
                    }
                }
                vo.setOvdReasonCdNm(ovdReasonCdNm);
            }
            if (orgMap != null && orgMap.containsKey(vo.getBuOrgCd())) {
                vo.setBuOrgCdNm(orgMap.get(vo.getBuOrgCd()));
            }
            if (commStsCdMap != null && commStsCdMap.containsKey(vo.getCommStsCd())) {
                vo.setCommStsCd(commStsCdMap.get(vo.getCommStsCd()));
            }
            
            if (vo.getCommSec() != null && vo.getCommSec()>0) {
            	vo.setCommSecDtl(DateUtils.parseIntToDate(vo.getCommSec()));//通话时长格式化
            }
            
        }
    }

    /**
     * 根据客户ID查询客户联系人信息
     *
     * @param idList
     * @return
     */
    @Override
    public List<CstContactInfoDTO> searchCstLkMan(List<Long> idList) throws BaseException {
        return customerQueryApiService.searchCstContactInfo(idList);
    }

    /**
     * 导出沟通记录
     *
     * @param condition
     * @return
     * @throws BaseException
     */
    public DataResultVO exportCommRecList(RskCommRecQueryCondition condition) throws BaseException {
        if(condition==null){
           condition=new RskCommRecQueryCondition();
        }
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        DataResultDTO resultDTO = rskCommRecApiService.exportCommRecList(condition);
        if(null!=resultDTO){
            return new DataResultVO(Integer.parseInt(resultDTO.getCode()),resultDTO.getInfo(),resultDTO.getData());
        }else{
            return new DataResultVO(BaseConstant.IS_YESNO_NO,"数据导出异常");
        }
    }
    /**
     * 逾期催收批量外呼
     * @param idList
     * @return
     */
    @Override
    public DataResultVO ovdOutboundList(RskCommRecQueryCondition condition)throws BaseException{
    	if(condition == null || CollectionUtils.isEmpty(condition.getCstIds())){
    		return new DataResultVO(BaseConstant.IS_YESNO_NO,"查询参数异常");
    	}
    	DataResultDTO resultDTO = rskCommRecApiService.ovdOutbroundList(condition);
        if(null!=resultDTO){
            return new DataResultVO(Integer.parseInt(resultDTO.getCode()),resultDTO.getInfo(),resultDTO.getData());
        }else{
            return new DataResultVO(BaseConstant.IS_YESNO_NO,"期催收批量外呼");
        }
    }
    /**
     * 外呼推送话单 批量修改状态
     */
    @Override
    public DataResultVO updateCommStsByTaskId(List<RskCommRecDTO> listDto)throws BaseException{
    	if(CollectionUtils.isNotEmpty(listDto)){
    		DataResultDTO resultDTO = this.rskCommRecApiService.updateCommStsByTaskId(listDto);
    		if(null!=resultDTO){
                return new DataResultVO(Integer.parseInt(resultDTO.getCode()),resultDTO.getInfo(),resultDTO.getData());
            }else{
                return new DataResultVO(BaseConstant.IS_YESNO_NO,"外呼推送话单 批量修改状态");
            }
    	}else{
    		 return new DataResultVO(BaseConstant.IS_YESNO_NO,"数据为空");
    	}
    }
    /**
     * 起租提醒外呼
     */
    @Override
    public DataResultVO toStartRent(CapRemindDataInfoQueryCondition condition)throws BaseException{
    	if(condition == null ){
    		return new DataResultVO(BaseConstant.IS_YESNO_NO,"查询参数异常");
    	}
    	DataResultDTO resultDTO = rskCommRecApiService.toStartRent(condition);
        if(null!=resultDTO){
            return new DataResultVO(Integer.parseInt(resultDTO.getCode()),resultDTO.getInfo(),resultDTO.getData());
        }else{
            return new DataResultVO(BaseConstant.IS_YESNO_NO,"起租提醒 返回结果为空");
        }
    }

    /**
     * 添加数据权限
     *
     * @param condition 查询条件
     * @return
     * @throws BaseException
     */
    public void setDataAuth(RskCommRecQueryCondition condition) throws BaseException {
        if (null != condition) {
            List<SysUsrDatAuthRDTO> list = this.priorityApiService.searchSysUsrDatAuthRWithOrgCdList(condition.getUsrId(), null, condition.getSysCd());
            StringBuffer sb = new StringBuffer();
            for (SysUsrDatAuthRDTO dto : list) {
                if(SplSystemConstant.DEFAULT_ORG_CD.equals(dto.getOrgCd())){
                    return;
                }
                if (sb != null && sb.length() > 0) {
                    sb.append(" OR ");
                }
                if (dto.getIsChg() == 1) {//是否主管 1.是 0.否
                    sb.append(" T.CST_MGR_ORG_CD LIKE '" + dto.getOrgCd() + "'||'%' ");
                } else {
                    sb.append(" T.CST_MGR_ORG_CD LIKE '" + dto.getOrgCd() + "'||'_%' ");
                }
            }

            if(CollectionUtils.isNotEmpty(list)){
                sb.insert(0, "((");
                sb.append(") AND T.CST_MGR_ID!=" + condition.getUsrId() + ") OR ");
                sb.append(" T.CST_MGR_ID=" + condition.getUsrId());
            }
            condition.setAccessCtrl(sb.toString());
        }
    }
}
